package com.smm.imgServer.util;

import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.geom.AffineTransform;
import java.awt.image.AffineTransformOp;
import java.awt.image.BufferedImage;
import java.io.File;

import javax.imageio.ImageIO;

/**
 * 图像处理类.
 * 
 * @author nagsh
 * 
 */
public class ImageProcesUtil {

	String openUrl; // 原始图片打开路径
	String saveUrl; // 新图保存路径
	String saveName; // 新图名称
	String suffix; // 新图类型 只支持gif,jpg,png

	public ImageProcesUtil(String openUrl, String saveUrl, String saveName,
			String suffix) {
		this.openUrl = openUrl;
		this.saveName = saveName;
		this.saveUrl = saveUrl;
		this.suffix = suffix;
	}

	/**
	 * 图片缩放.
	 * 
	 * @param width
	 *            需要的宽度
	 * @param height
	 *            需要的高度
	 * @throws Exception
	 */
	public void zoom(int width, int height) throws Exception {
		double sx = 0.0;
		double sy = 0.0;

		File file = new File(openUrl);
		if (!file.isFile()) {
			throw new Exception("ImageDeal>>>" + file + " 不是一个图片文件!");
		}
		BufferedImage bi = ImageIO.read(file); // 读取该图片
		// 计算x轴y轴缩放比例--如需等比例缩放，在调用之前确保参数width和height是等比例变化的
		sx = (double) width / bi.getWidth();
		sy = (double) height / bi.getHeight();

		AffineTransformOp op = new AffineTransformOp(
				AffineTransform.getScaleInstance(sx, sy), null);
		File sf = new File(saveUrl, saveName + "." + suffix);
		Image zoomImage = op.filter(bi, null);
		try {
			ImageIO.write((BufferedImage) zoomImage, suffix, sf); // 保存图片
		} catch (Exception e) {
			e.printStackTrace();
		}

	}
}
